<template>
  <div id="watermark-container" ref="watermarkContainer">
    <slot></slot>
  </div>
</template>

<script setup lang="ts">
import { useWatermarkBg } from './useWatermarkBg';
import { defineProps, useTemplateRef, onMounted, onUnmounted } from "vue"
const props = defineProps({
  text: {
    require: true,
    type: String,
    default: 'watermark'
  },
  fontSize: {
    type: Number,
    default: 50
  },
  gap: {
    type: Number,
    default: 15
  }
})

const bg = useWatermarkBg(props);
let div: HTMLDivElement;
const watermarkRef = useTemplateRef('watermarkContainer');
// 重置水印
function resetWatermark() {
  if (!watermarkRef.value) return;
  if (div) {
    div.remove();
  }
  const { base64, size } = bg;

  div = document.createElement('div');
  div.style.position = "absolute";
  div.style.backgroundImage = `url(${base64})`;
  div.style.backgroundSize = `${size.width}px ${size.height}px`;
  div.style.backgroundRepeat = "repeat";
  div.style.pointerEvents = "none";
  div.style.zIndex = "9999";
  div.style.inset = "0";
  watermarkRef.value?.appendChild(div);
}

const ob = new MutationObserver((entries) => {
  for (const entry of entries) {
    // 处理被删除情况
    for (const node of entry.removedNodes) {
      if (node === div) {
        resetWatermark();
        return;
      }
    }
    // 处理被修改情况
    if (entry.target === div) {
      resetWatermark();
    }
  }
})
onMounted(() => {
  resetWatermark();
  const content = watermarkRef.value;
  if (content) {
    ob.observe(content, { childList: true, subtree: true, attributes: true });
  }
})

onUnmounted(() => {
  ob.disconnect();
})
</script>

<style lang="scss" scoped>
#watermark-container{
  display: inline - block;
  position: relative;
}
</style>